package com.zjw.socket.demo.starter.messageService.service;

import com.zjw.socket.demo.starter.annotation.core.Bean;
import com.zjw.socket.demo.starter.annotation.core.Inject;
import com.zjw.socket.demo.starter.messageService.Message;
import com.zjw.socket.demo.starter.messageService.SystemMessageType;

import java.nio.ByteBuffer;
import java.util.List;

@Bean
public class SystemMessageService {

  @Inject(query = "SimpleUserPool")
  public IUserPool userPool;
  @Inject
  public LoginService loginService;
  @Inject
  public UserService userService;

  @Inject(query = "MemoryMessageDataBase")
  public IMessageDataBase dataBase;

  @Inject(query = "MessageTransferService")
  public MessageTransferService messageTransferService;

  //处理系统消息，这可以理解成client-service交互
  //此函数可以异步执行，
  public void processSystemMessage(Message message, IConnectSession sender) {
    int type = message.getType();
    long fromId = message.getFromId();

    switch (type) {
      case SystemMessageType.PING:
        //recover service
        message.setFromId(0);
        message.setToId(fromId);
        message.setType(SystemMessageType.PONG);
        sender.writeMessage(message);
        break;

      case SystemMessageType.LOGIN:
        loginService.login(fromId, message, sender);
        break;

      case SystemMessageType.REGISTER:
        loginService.register(fromId, message, sender);
        break;

      case SystemMessageType.USER_CONNECT_CLOSE:
      case SystemMessageType.UNLOGIN:
        loginService.unlogin(fromId);
        break;

      case SystemMessageType.REQUEST_SERVICE_CACHE_MESSAGE_LENGTH:
        message.setType(SystemMessageType.RESPONSE_SERVICE_CACHE_MESSAGE_LENGTH);
        List<Message> messageList = dataBase.getMessageList(fromId);
        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.putInt(messageList == null ? 0 : messageList.size());
        message.setBytes(buffer.array());
        sender.writeMessage(message);
        break;

      case SystemMessageType.REQUEST_SERVICE_CACHE_MESSAGE:
        for (Message message1 : dataBase.getMessageList(fromId)) {
          sender.writeMessage(message1);
        }
        break;

      case SystemMessageType.CLEAR_SERVICE_CACHE_MESSAGE:
        dataBase.removeMessageList(fromId);
        break;

      case SystemMessageType.REQUEST_USER_INFO:
        loginService.requireUserInfo(message);
        break;

      case SystemMessageType.REQUEST_ADD_FRIEND:
        userService.addFriend(message, sender);
        break;

      case SystemMessageType.REQUEST_OTHERS_USER_INFO:
        userService.queryOtherUser(message, sender);
        break;
    }
  }

  public boolean isSystemMessage(int type) {
    return type >= 30000;
  }
}
